//
//  AreaChooseController.m
//  QRMaster
//
//  Created by myApple on 16/3/1.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "AreaChooseController.h"
#import "ChineseString.h"
#import "AreaChooseCell.h"
#import "pinyin.h"

@interface AreaChooseController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView * areaTabelView;
    NSMutableArray * indexArray;
    NSMutableArray * letterResultArr;
    NSString * areaCodeIdString;//区号
    NSString * areaString;//国家或者地址
    NSMutableDictionary * areaDict;
}

@end

@implementation AreaChooseController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"areaOrCountry", nil);
    // Do any additional setup after loading the view.
   areaDict = [[NSMutableDictionary alloc]init];
    for (int i = 0 ; i < AreaArray.count; i ++) {
        [areaDict setValue:AreaCodeArray[i] forKey:AreaArray[i]];
    }
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self prepareData];
    [self prepareTableView];
}

-(void)prepareData
{
    indexArray = [[NSMutableArray alloc]init];
    indexArray = [self indexArray:AreaArray];
    letterResultArr = [[NSMutableArray alloc]init];
    letterResultArr = [self LetterSortArray:AreaArray];
}

-(void)prepareTableView
{
    areaTabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
    areaTabelView.delegate = self;
    areaTabelView.dataSource = self;
    [self.view addSubview:areaTabelView];
}


#pragma mark ------------ uitableviewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return indexArray.count;
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return indexArray;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return indexArray[section];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray * rowCount = letterResultArr[section];
    return rowCount.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40.0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 15.0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * cellId = @"cellId";
    AreaChooseCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[AreaChooseCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    
    NSArray * rowInfoArr = letterResultArr[indexPath.section];
    cell.areaNameString = rowInfoArr[indexPath.row];
    cell.areaCodeIdString = [areaDict objectForKey:cell.areaNameString];
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray * areaRowArray = letterResultArr[indexPath.section];
    areaString = areaRowArray[indexPath.row];
    for (int i = 0 ; i < AreaArray.count; i++) {
        if ([areaString isEqualToString:AreaArray[i]]) {
            areaCodeIdString = AreaCodeArray[i];
        }
    }
    if (_areaCode) {
        _areaCode(areaCodeIdString,areaString);
    }
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark -------------返回tableview右方的indexarray
-(NSMutableArray *)indexArray:(NSArray *)stringArr
{
    NSMutableArray *tempArray = [self ReturnSortChineseArrar:stringArr];
    NSMutableArray *A_Result = [NSMutableArray array];
    NSString *tempString ;
    
    for (NSString* object in tempArray)
    {
        NSString *pinyin = [((ChineseString*)object).pinYin substringToIndex:1];
        //不同
        if(![tempString isEqualToString:pinyin])
        {
            [A_Result addObject:pinyin];
            tempString = pinyin;
        }
    }
    return A_Result;
}

-(NSMutableArray*)ReturnSortChineseArrar:(NSArray*)stringArr
{
    //获取字符串中文字的拼音首字母并与字符串共同存放
    NSMutableArray *chineseStringsArray=[NSMutableArray array];
    for(int i=0;i<[stringArr count];i++)
    {
        ChineseString *chineseString = [[ChineseString alloc]init];
        chineseString.string = [NSString stringWithString:[stringArr objectAtIndex:i]];
        if(chineseString.string == nil){
            chineseString.string = @"";
        }
        //去除两端空格和回车
        chineseString.string  = [chineseString.string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
        //这里我自己写了一个递归过滤指定字符串   RemoveSpecialCharacter
//        chineseString.string = [self RemoveSpecialCharacter:chineseString.string];
        
        
        //判断首字符是否为字母
        NSString *regex = @"[A-Za-z]+";
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
        NSString *initialStr = [chineseString.string length]?[chineseString.string substringToIndex:1]:@"";
        if ([predicate evaluateWithObject:initialStr])
        {
            //首字母大写
            chineseString.pinYin = [chineseString.string capitalizedString] ;
        }else{
            if(![chineseString.string isEqualToString:@""]){
                NSString *pinYinResult = [NSString string];
                for(int j=0;j<chineseString.string.length;j++){
                NSString *singlePinyinLetter = [[NSString stringWithFormat:@"%c",
                                                     
                                                     pinyinFirstLetter([chineseString.string characterAtIndex:j])]uppercaseString];
                 
                    
                    pinYinResult = [pinYinResult stringByAppendingString:singlePinyinLetter];
                }
                chineseString.pinYin = pinYinResult;
            }else{
                chineseString.pinYin = @"";
            }
        }
        [chineseStringsArray addObject:chineseString];
    }
    //按照拼音首字母对这些Strings进行排序
    NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"pinYin" ascending:YES]];
    [chineseStringsArray sortUsingDescriptors:sortDescriptors];
    return chineseStringsArray;
}

#pragma mark - 返回一组字母排序数组
-(NSMutableArray*)SortArray:(NSArray*)stringArr
{
    NSMutableArray *tempArray = [self ReturnSortChineseArrar:stringArr];
    
    //把排序好的内容从ChineseString类中提取出来
    NSMutableArray *result = [NSMutableArray array];
    for(int i=0;i<[stringArr count];i++){
        [result addObject:((ChineseString*)[tempArray objectAtIndex:i]).string];
    }
    return result;
}


//过滤指定字符串   里面的指定字符根据自己的需要添加 过滤特殊字符
-(NSString*)RemoveSpecialCharacter: (NSString *)str {
    NSRange urgentRange = [str rangeOfCharacterFromSet: [NSCharacterSet characterSetWithCharactersInString: @",.？、 ~￥#&<>《》()[]{}【】^@/￡¤|§¨「」『』￠￢￣~@#&*（）——+|《》$_€"]];
    if (urgentRange.location != NSNotFound)
    {
        return [self RemoveSpecialCharacter:[str stringByReplacingCharactersInRange:urgentRange withString:@""]];
    }
    return str;
}

#pragma mark - 返回地区
-(NSMutableArray*)LetterSortArray:(NSArray*)stringArr
{
    NSMutableArray *tempArray = [self ReturnSortChineseArrar:stringArr];
    NSMutableArray *LetterResult = [NSMutableArray array];
    NSMutableArray *item = [NSMutableArray array];
    NSString *tempString;
    //拼音分组
    for (NSString* object in tempArray) {
        
        NSString *pinyin = [((ChineseString*)object).pinYin substringToIndex:1];
        NSString *string = ((ChineseString*)object).string;
        //不同
        if(![tempString isEqualToString:pinyin])
        {
            //分组
            item = [NSMutableArray array];
            [item  addObject:string];
            [LetterResult addObject:item];
            //遍历
            tempString = pinyin;
        }else//相同
        {
            [item  addObject:string];
        }
    }
    return LetterResult;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
